package mwa.cs.hh.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.CustHHDAO;
import mwa.cs.dao.RouteDAO;
import mwa.cs.dao.RouteScheduleMasterDAO;
import mwa.cs.dao.ZoneDAO;
import mwa.cs.database.Database;

public class CS36001Srvl extends HttpServlet {

	private Database db;
	private String[] vaMonthThaiArray = new String[]{"ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."};
    private int vnSiteId;
    private int vnUserId;
	public CS36001Srvl() {
		super();
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String vaProcessType = request.getParameter("process_type");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		if (vaProcessType.equals("getDataTable")) {
			getDataTable(request, response);
		} else if (vaProcessType.equals("getZone")) {
			getZone(request, response);
		} else if (vaProcessType.equals("getRout")) {
			getRout(request, response);
		}
		
	}

	private void getZone(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		JSONObject voObject = new JSONObject();
		PrintWriter voOut = response.getWriter();
		
		String[] vaMessage = null, vaValue = null;
		
		try
		{
			this.db = new Database();
		}
    	catch(Exception ex)
    	{
    		voObject.put("messages", null);
    		voObject.put("values", null);
    		voOut.print(voObject.toJSONString());
    		return;
    	}
		
		ZoneDAO voZoneDAO = new ZoneDAO(db);
		List<Map<String, Object>> voZoneList = voZoneDAO.findZoneBySite(vnSiteId);
		
		vaValue = new String[voZoneList.size()];
		vaMessage = new String[voZoneList.size()];
		
		for (int i = 0; i < voZoneList.size(); i++) {
			Map<String, Object> obj = voZoneList.get(i);	
			vaValue[i] = obj.get("ZONE_ID").toString(); 
			vaMessage[i] = obj.get("ZONE_NAME").toString();
		}
		
		JSONArray voList = new JSONArray();
		if (vaMessage != null) {
			for (int i = 0; i < vaMessage.length; i ++) {
				voList.add(vaMessage[i]);
			}
		}
		
		voObject.put("messages", voList);
		
		JSONArray voList2 = new JSONArray();
		if (vaValue != null) {
			for (int i = 0; i < vaValue.length; i ++) {
				voList2.add(vaValue[i]);
			}
		}
		
		voObject.put("values", voList2);
		
		db.close();
		
		voOut.print(voObject.toJSONString());
		
	}

	private void getRout(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");

		JSONObject voObject = new JSONObject();
		PrintWriter voOut = response.getWriter();
		
		String[] vaMessage = null, vaValue = null;
		
		try
		{
			this.db = new Database();
		}
    	catch(Exception ex)
    	{
    		voObject.put("messages", null);
    		voObject.put("values", null);
    		voOut.print(voObject.toJSONString());
    		return;
    	}
		
		int vnZoneId = Integer.parseInt(request.getParameter("vnZoneId").toString());
		
		RouteDAO voRouteDAO = new RouteDAO(db);
		List<Map<String, Object>> voRoutList = voRouteDAO.findRouteByZone(vnSiteId, vnZoneId);
		
		vaValue = new String[voRoutList.size()];
		vaMessage = new String[voRoutList.size()];
		
		for (int i = 0; i < voRoutList.size(); i++) {
			Map<String, Object> obj = voRoutList.get(i);	
			vaValue[i] = obj.get("ROUTE_ID").toString(); 
			vaMessage[i] = obj.get("ROUTE_DESCRIPTION").toString();
		}
		
		JSONArray voList = new JSONArray();
		if (vaMessage != null) {
			for (int i = 0; i < vaMessage.length; i ++) {
				voList.add(vaMessage[i]);
			}
		}
		
		voObject.put("messages", voList);
		
		JSONArray voList2 = new JSONArray();
		if (vaValue != null) {
			for (int i = 0; i < vaValue.length; i ++) {
				voList2.add(vaValue[i]);
			}
		}
		
		voObject.put("values", voList2);
		
		db.close();
		
		voOut.print(voObject.toJSONString());

	}

	private void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		
		PrintWriter voOut = response.getWriter();	
		
		String vaCon0 = request.getParameter("sSearch_0"); // ลำดับ
		String vaCon1 = request.getParameter("sSearch_1"); // เขต
		String vaCon2 = request.getParameter("sSearch_2"); // เส้นทางเริ่ม
		String vaCon3 = request.getParameter("sSearch_3"); // เส้นทางสิ้นสุด
		
		try
		{
			this.db = new Database();	
		}
		catch(Exception ex)
		{
			voObject.put("iTotalRecords", 0);
			voObject.put("iTotalDisplayRecords", 0);
			voObject.put("aaData", voRow);
			voOut.print(voObject.toJSONString());
			return;
		}
		
		if(vaCon1.length() > 0 || vaCon2.length() > 0 || vaCon3.length() > 0)
		{
			CustHHDAO voCustDao = new CustHHDAO(db);
			String paPeriodMonth = voCustDao.findMaxMonth(vnSiteId);
			String paPeriodYear = voCustDao.findMaxYear(vnSiteId);
			
			int pnZoneId = Integer.parseInt(vaCon1);
			int pnRouteIdFrom = Integer.parseInt(vaCon2);
			int pnRouteIdTo = Integer.parseInt(vaCon3);
			
			String[] vaColumnsASC = { "z.ZONE_NAME ASC", "r.ROUTE_ID ASC" };
			String[] vaColumnsDESC = { "z.ZONE_NAME DESC", "r.ROUTE_ID DESC" };

			String paSortColumn = " r.ROUTE_ID ASC ";
			int vnSortColumn = Integer.parseInt(request.getParameter("iSortCol_0")); // 0, 1, 2, 3
			String vaSortDirection = request.getParameter("sSortDir_0");

			if (vaSortDirection.equals("asc")) {
				try{ paSortColumn = vaColumnsASC[vnSortColumn-1]; }
				catch(Exception ex){}
			}
			if (vaSortDirection.equals("desc")) {
				try{ paSortColumn = vaColumnsDESC[vnSortColumn-1]; }
				catch(Exception ex){}
			}
			
			RouteScheduleMasterDAO voRouteScheduleMasterDAO = new RouteScheduleMasterDAO(db);
			List<Map<String, Object>> voRsmList = voRouteScheduleMasterDAO.findRouteBySizeZoneRouteMonthYear(vnSiteId, pnZoneId, pnRouteIdFrom, pnRouteIdTo, paPeriodMonth, paPeriodYear, paSortColumn);
			
			if(voRsmList != null && voRsmList.size() > 0)
			{
				for(int i=0; i<voRsmList.size(); i++)
				{
					voColumn = new JSONArray();
					Map<String, Object> rsmObj = voRsmList.get(i);
					
					String ZONE_NAME = rsmObj.get("ZONE_NAME") == null ? "" : rsmObj.get("ZONE_NAME").toString();
					String ROUTE_DESCRIPTION = rsmObj.get("ROUTE_DESCRIPTION") == null ? "" : rsmObj.get("ROUTE_DESCRIPTION").toString();
					String TOTAL_RECORD = rsmObj.get("TOTAL_RECORD") == null ? "" : rsmObj.get("TOTAL_RECORD").toString();
					String INSER_DATE = rsmObj.get("INSER_DATE") == null ? "" : rsmObj.get("INSER_DATE").toString();
					String TOTAL_DOWNLOAD = rsmObj.get("TOTAL_DOWNLOAD") == null ? "" : rsmObj.get("TOTAL_DOWNLOAD").toString();
					String DOWNLOAD_DATE = rsmObj.get("DOWNLOAD_DATE") == null ? "" : rsmObj.get("DOWNLOAD_DATE").toString();
					String TOTAL_UPLOAD = rsmObj.get("TOTAL_UPLOAD") == null ? "" : rsmObj.get("TOTAL_UPLOAD").toString();
					String UPLOAD_DATE = rsmObj.get("UPLOAD_DATE") == null ? "" : rsmObj.get("UPLOAD_DATE").toString();
					
					// เตรียมข้อมูลอ่านมาตร
					String vaStrRecord = "";
					if(TOTAL_RECORD.trim().length() == 0 || TOTAL_RECORD.trim().equals("0"))
					{
						vaStrRecord = "<div><font color='red'><i class='glyphicon glyphicon-remove'></i></font></div><div><font color='red'>ยังไม่ดำเนินการ</font></div>";
					}
					else
					{
						String strDate = convertToThaiDateString(INSER_DATE);
						vaStrRecord = "<div><font color='green'><i class='glyphicon glyphicon-ok'></i></font></div><div><font color='green'>" + strDate + "</font></div>";
					}
					
					// ยืนยันการจัดทำใบแจ้งหนี้
					String vaStrDownload = "";
					if(TOTAL_DOWNLOAD.trim().length() == 0 || TOTAL_DOWNLOAD.trim().equals("0"))
					{
						vaStrDownload = "<div><font color='red'><i class='glyphicon glyphicon-remove'></i></font></div><div><font color='red'>ยังไม่ดำเนินการ</font></div>";
					}
					else
					{
						String vaStrDate = convertToThaiDateString(DOWNLOAD_DATE);
						vaStrDownload = "<div><font color='green'><i class='glyphicon glyphicon-ok'></i></font></div><div><font color='green'>" + vaStrDate + "</font></div>";
					}
					
					// ตั้งหนี้
					String vaStrUpload = "";
					if(TOTAL_UPLOAD.trim().length() == 0 || TOTAL_UPLOAD.trim().equals("0"))
					{
						vaStrUpload = "<div><font color='red'><i class='glyphicon glyphicon-remove'></i></font></div></div><div><font color='red'>ยังไม่ดำเนินการ</font></div>";
					}
					else
					{
						String strDate = convertToThaiDateString(UPLOAD_DATE);
						vaStrUpload = "<div><font color='green'><i class='glyphicon glyphicon-ok'></i></font></div><div><font color='green'>" + strDate + "</font></div>";
					}
					
					voColumn.add(i+1);		// ลำดับ
					voColumn.add(ZONE_NAME);		// เขต
					voColumn.add(ROUTE_DESCRIPTION);		// เส้นทาง
					voColumn.add(vaStrRecord);		// เตรียมข้อมูลอ่านมาตร
					voColumn.add(vaStrDownload);		// ยืนยันการจัดทำใบแจ้งหนี้
					voColumn.add(vaStrUpload);		// ตั้งหนี้
					
					voRow.add(voColumn);
				}
				
				voObject.put("iTotalRecords", voRsmList.size());
				voObject.put("iTotalDisplayRecords", voRsmList.size());
				voObject.put("aaData", voRow);
				
				db.close();
				
				voOut.print(voObject.toJSONString());
			}
			else
			{
				voObject.put("iTotalRecords", 0);
				voObject.put("iTotalDisplayRecords", 0);
				voObject.put("aaData", voRow);
				
				db.close();
				
				voOut.print(voObject.toJSONString());
			}
		}
		else
		{
			voObject.put("iTotalRecords", 0);
			voObject.put("iTotalDisplayRecords", 0);
			voObject.put("aaData", voRow);
			
			db.close();
			
			voOut.print(voObject.toJSONString());
		}
	}
	
	public String convertToThaiDateString(String pnStrDate)
	{
		String vaStrDate = "วันที่ ";
		
		try
		{
			int vnYear = Integer.parseInt(pnStrDate.substring(0, 4));
			int vnMonth = Integer.parseInt(pnStrDate.substring(4, 6));
			int vnDay = Integer.parseInt(pnStrDate.substring(6, 8));
			
			pnStrDate += vnDay + " " + vaMonthThaiArray[vnMonth - 1] + " " + vnYear;
		}
		catch(Exception ex){}
		
		return pnStrDate; 
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
